﻿using JWT实践webapi.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace JWT实践webapi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly IOptionsSnapshot<JWTSetting> JWTSettingOpt;

        public LoginController(IOptionsSnapshot<JWTSetting> jWTSettingOpt)
        {
            JWTSettingOpt = jWTSettingOpt;
        }

        [HttpPost]
        public ActionResult Login(string name, string pwd)
        {
            if (name == "yhs" && pwd == "123456")
            {
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.NameIdentifier, "1"));
                claims.Add(new Claim(ClaimTypes.Name, name));

                string key = JWTSettingOpt.Value.SigningKey;
                DateTime expires = DateTime.Now.AddSeconds(JWTSettingOpt.Value.ExpireSeconds);
                byte[] secBytes = Encoding.UTF8.GetBytes(key);
                var secKey = new SymmetricSecurityKey(secBytes);
                var credentials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature);
                var tokenDescriptor = new JwtSecurityToken(claims: claims,
                    expires: expires, signingCredentials: credentials);
                string jwt = new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
                return Ok(jwt);

            }
            else
            {
                return BadRequest("生成jwt失败");
            }
        }
    }
}
